<template>
  <div class="article-create-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>创建文章</span>
          <el-button type="primary" @click="submitForm">发布文章</el-button>
        </div>
      </template>

      <el-form :model="articleForm" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" maxlength="100" show-word-limit/>
        </el-form-item>

        <el-form-item label="浏览量" prop="views">
          <el-input v-model="articleForm.views" type="number" maxlength="100" show-word-limit/>
        </el-form-item>

        <el-form-item label="首图URL" prop="pictureUrl">
          <el-input v-model="articleForm.pictureUrl" placeholder="请输入首图URL地址" maxlength="100" show-word-limit/>
        </el-form-item>

        <el-form-item label="文章分类" prop="categoryId">
          <el-select v-model="articleForm.categoryId" placeholder="请选择文章分类" style="width: 100%">
            <el-option
                v-for="category in categoryOptions"
                :key="category.id"
                :label="category.name"
                :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="文章标签" prop="tagIds">
          <el-select
              v-model="articleForm.tagIds"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择文章标签（可多选）"
              style="width: 100%"
          >
            <el-option
                v-for="tag in tagOptions"
                :key="tag.id"
                :label="tag.name"
                :value="tag.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="预览内容" prop="previewContent">
          <div class="editor-preview-container">
            <v-md-editor v-model="articleForm.previewContent" height="300px" placeholder="请输入文章预览内容"></v-md-editor>
          </div>
        </el-form-item>


        <el-form-item label="主体内容" prop="mainContent">
          <div class="editor-container">
            <v-md-editor v-model="articleForm.mainContent" height="300px" placeholder="请输入文章内容"
                         @change="updateWordCount"></v-md-editor>
            <div class="word-count">
              字数统计：{{ articleForm.wordCount }} 字
            </div>
          </div>
        </el-form-item>


        <el-form-item>
          <el-row class="row-container">
            <el-col :span="4">
              <el-form-item label="是否公开" prop="isPublished">
                <el-switch v-model="articleForm.isPublished"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="是否置顶" prop="isTop">
                <el-switch v-model="articleForm.isTop"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="是否赞赏" prop="isAppreciation">
                <el-switch v-model="articleForm.isAppreciation"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="是否评论" prop="isComment">
                <el-switch v-model="articleForm.isComment"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <div class="form-actions">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="info" @click="saveAsDraft">保存草稿</el-button>
        <el-button type="primary" @click="submitForm">发布文章</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {useRouter} from 'vue-router'
import {findAllTag} from '@/api/tag'
import {findAllCategory} from '@/api/category'
import {saveBlog} from '@/api/blog'

export default {
  name: "ArticleCreate",

  setup() {
    const router = useRouter()
    const formRef = ref(null)

    // 文章表单数据
    const articleForm = reactive({
      title: '',              // 文章标题
      status: 1,              // 0: 草稿, 1: 发布
      previewContent: '',     // 预览内容
      mainContent: '',        // 主体内容
      views: 0,               // 浏览量
      wordCount: 0,           // 文章字数
      pictureUrl: '',         // 首图URL地址
      isPublished: false,     // 公开和私密
      isTop: false,           // 是否置顶
      isAppreciation: false,  // 是否开启赞赏
      isComment: false,       // 是否开启评论
      userId: '',             // 作者ID
      categoryId: '',         // 文章分类ID
      tagIds: [],             // 标签ID列表
    })

    // 表单验证规则
    const rules = {
      title: [
        {required: true, message: '请输入文章标题', trigger: 'blur'},
        {min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur'}
      ],
      previewContent: [
        {required: true, message: '请输入预览内容', trigger: 'blur'},
      ],
      mainContent: [
        {required: true, message: '请输入文章内容', trigger: 'blur'}
      ],
      views: [
        {required: true, message: '请输入首图URL地址', trigger: 'blur'}
      ],
      pictureUrl: [
        {required: true, message: '请输入浏览量', trigger: 'blur'}
      ],
      categoryId: [
        {required: true, message: '请选择文章分类', trigger: 'change'}
      ],

    }

    // 分类选项
    const categoryOptions = ref([])

    // 标签选项
    let tagOptions = ref([])

    onMounted(() => {
      findAllCategory().then(res => {
        categoryOptions.value = res.data
      })

      findAllTag().then(res => {
        tagOptions.value = res.data
      })
    })

    // 更新字数统计
    const updateWordCount = () => {
      const content = articleForm.mainContent || ''
      // 中文和英文单词都计算为一个字
      articleForm.wordCount = content.replace(/\s/g, '').length
    }

    // 提交表单
    const submitForm = () => {
      if (!formRef.value) return

      formRef.value.validate((valid) => {
        if (valid) {
          articleForm.status = 1 // 设置为已发布状态
          articleForm.userId = JSON.parse(localStorage.getItem('user') || '{}').id // 获取用户ID

          saveBlog(articleForm).then(res => {
            console.log('res', res)
            ElMessage.success('文章发布成功!')
            router.push('/article') // 跳转到文章列表页
          })

        } else {
          ElMessage.error('请完善表单信息!')
          return false
        }
      })
    }

    // 保存为草稿
    const saveAsDraft = () => {
      articleForm.status = 0 // 设置为草稿状态
      articleForm.userId = JSON.parse(localStorage.getItem('user') || '{}').id // 获取用户ID
      console.log(articleForm)
      saveBlog(articleForm).then(res => {
        console.log('res', res)
        ElMessage.success('草稿保存成功!')
      })
    }

    // 重置表单
    const resetForm = () => {
      if (!formRef.value) return
      formRef.value.resetFields()
      articleForm.wordCount = 0
    }

    return {
      formRef,
      articleForm,
      rules,
      categoryOptions,
      tagOptions,
      updateWordCount,
      submitForm,
      saveAsDraft,
      resetForm
    }
  }
}
</script>

<style scoped>
.article-create-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-preview-container {
  width: 100%;
}

.editor-container {
  position: relative;
  width: 100%;
}

.row-container {
  width: 100%;
}

.word-count {
  position: absolute;
  bottom: 5px;
  right: 10px;
  font-size: 12px;
  color: #909399;
}

.form-actions {
  margin-top: 20px;
  text-align: center;
}
</style>
